//
//  MeasureViewController.m
//  Romens.XSBalance
//
//  Created by 李美东 on 16/2/23.
//  Copyright © 2016年 孙博. All rights reserved.
//
#import "AppDelegate.h"
#import "DeviceSearchController.h"
#import "CBPeripheralAdditions.h"
#import "SSBLEDeviceManager.h"
#import "ToolHelper.h"
#import "MeasureViewController.h"
#import "DeviceSearchCell.h"
#import "MainHomeViewTabBarController.h"
#import "DeviceInfo.h"
#import "MJExtension.h"
#import "RuntimeStatus.h"
@interface DeviceSearchController ()<SSBLEDeviceDelegate,UITableViewDataSource, UITableViewDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_list;
    NSMutableDictionary *_deviceIDToPeripheralMap;
    CBPeripheral *_selectedPeripheral;
    UIButton * _jumpButton;
}
@end

@implementation DeviceSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadView1];
//    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:self action:nil];
//    self.navigationItem.leftBarButtonItem = leftButton;
    
    if (_IsJump==nil) {
        _jumpButton.hidden=YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)loadView1 {
    self.view.layer.contents=(id)[UIImage imageNamed:@"tips_bg"].CGImage;
    _tableView = [[UITableView alloc]init];
    _tableView.translatesAutoresizingMaskIntoConstraints=NO;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.bounces = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.alpha=0;
    [self.view addSubview:_tableView];
    
    _jumpButton=[[UIButton alloc]init];
    _jumpButton.translatesAutoresizingMaskIntoConstraints=NO;
    _jumpButton.backgroundColor=SystemColor;
    _jumpButton.layer.cornerRadius = 5.0f;//圆角半径
    [_jumpButton setTitle:NSLocalizedString(@"跳过", nil) forState:UIControlStateNormal];
    [_jumpButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_jumpButton addTarget:self action:@selector(jumpMeasure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_jumpButton];
    
    
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_tableView)  format:@"H:|[_tableView]|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_jumpButton)  format:@"H:|-8-[_jumpButton]-8-|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_tableView,_jumpButton)  format:@"V:|[_tableView]-[_jumpButton(40)]-8-|"]];
    
    _list = [NSMutableArray array];
    _deviceIDToPeripheralMap = [NSMutableDictionary dictionary];
}

-(void)jumpMeasure
{
    MainHomeViewTabBarController * mainVC=[[MainHomeViewTabBarController alloc]init];
    [self  presentViewController:mainVC animated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate.bleMgr addDelegate:self];
    [delegate.bleMgr scanPeripherals];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate.bleMgr removeDelegate:self];
}




//********************目前还不知道有什么用************************//
- (void)refreshClick:(id)sender {
    _list = [NSMutableArray array];
    _deviceIDToPeripheralMap = [NSMutableDictionary dictionary];
    [_tableView reloadData];
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate.bleMgr scanPeripherals];
}

#pragma mark--健康秤 delegate
//蓝牙搜索到周围的设备；
- (void)peripheralDidDiscover:(CBPeripheral *)peripheral {
    CBPeripheral *temp = [_deviceIDToPeripheralMap objectForKey:peripheral.deviceID];
    if (peripheral.newRSSI.intValue == 127) {
        return;
    }
    if (!temp) {
        temp = peripheral;
        [_list addObject:peripheral];
        [_deviceIDToPeripheralMap setObject:peripheral forKey:peripheral.deviceID];
    }
    temp.newRSSI = peripheral.newRSSI;
    
    dispatch_async(dispatch_get_main_queue(), ^(void){
        [_tableView reloadData];
        CGContextRef context = UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:1];
        _tableView.alpha=1;
        [UIView commitAnimations];
        
    });
}
- (void)reloadData {
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_list count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"DeviceSearchCell";
    DeviceSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[DeviceSearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    CBPeripheral *peripheral = [_list objectAtIndex:indexPath.row];
    int deviceType = peripheral.deviceType.intValue;
    if (deviceType == SSBLESENSSUNBODY)
    {
        cell.Name.text = @"香山体重秤";
    }
    else if (deviceType == SSBLESENSSUNFAT) {
        cell.Name.text =NSLocalizedString(@"再康健康秤", nil);
    }
    else
    {
        cell.Name.text =@"others";
    }
    cell.SerialNO.text=[NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"设备序列号", nil), peripheral.serialNO];
    cell.IndicateLight.value =(peripheral.newRSSI.intValue+102)*50/2100.0f;
    return cell;
}

#pragma mark - Table view delegate
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _selectedPeripheral = [_list objectAtIndex:indexPath.row];
    MainHomeViewTabBarController * mainVC=[[MainHomeViewTabBarController alloc]init];
    UINavigationController *nvc=mainVC.viewControllers.firstObject;
    MeasureViewController *vc = nvc.viewControllers.firstObject;
    vc.deviceID = _selectedPeripheral.deviceID;
    vc.advertiseName = _selectedPeripheral.advertiseName;
    vc.serialNO = _selectedPeripheral.serialNO;

    //   本地化存储 设备列表；
    DeviceInfo * info=[[DeviceInfo alloc]init];
    
    info.deviceID=_selectedPeripheral.deviceID;
    info.advertiseName=_selectedPeripheral.advertiseName;
    info.serialNO=_selectedPeripheral.serialNO;
    
    
    SCLAlertView *alert = [[SCLAlertView alloc] initWithNewWindow];
    alert.customViewColor = SystemColor;
    alert.iconTintColor =[UIColor whiteColor];
    UITextField *textField = [alert addTextField:nil];
    
    
    
    NSUserDefaults * defaults=[NSUserDefaults standardUserDefaults];
  //  [defaults removeObjectForKey:@"DeviceAlls"];
    NSString * jsonString=[defaults objectForKey:@"DeviceAlls"];
    NSMutableArray * deviceArray;
    
    
    if (jsonString==nil) {
        deviceArray=[[NSMutableArray alloc]init];
        textField.text=[NSString stringWithFormat:@"%@1",NSLocalizedString(@"再康健康秤", nil)] ;
        [alert addButton:NSLocalizedString(@"确定", nil) actionBlock:^(void)
         {
             if (textField.text==nil ||[textField.text isEqualToString:@""])
             {
             [self SHowMessage:NSLocalizedString(@"设备名称不可为空！", nil)  type:showWarning];
                 return ;
             }
             info.name=textField.text;
             vc.deviceName=textField.text;
             NSDictionary *UserDict = info.keyValues;
             [deviceArray addObject:UserDict];
             NSString*result= [ToolHelper  dictionaryToJson:deviceArray];
             [defaults setObject:result forKey:@"DeviceAlls"];
             [defaults synchronize];
             [[NSNotificationCenter defaultCenter] postNotificationName:@"UserChange" object:nil];
             [self  presentViewController:mainVC animated:YES completion:nil];
         }];
        [alert addButton:NSLocalizedString(@"取消", nil)  actionBlock:^(void){
            vc.deviceName=textField.text;
            [self  presentViewController:mainVC animated:YES completion:nil];
        }];
       [alert showEdit:self title:NSLocalizedString(@"系统提示", nil)  subTitle:NSLocalizedString(@"健康秤绑定", nil)  closeButtonTitle:nil duration:0.0f];
    }
    else
    {
        id array=[ToolHelper JsonToDictionary:jsonString];
        deviceArray=[NSMutableArray arrayWithArray:array];
    
    
        for (NSDictionary * information in deviceArray)
        {
            if ([[information objectForKey:@"deviceID"] isEqualToString:_selectedPeripheral.deviceID])
            {
                vc.deviceName=[information objectForKey:@"name"];
                break;
            }
            
            if ([information isEqual:[deviceArray lastObject]])
            {
                
                textField.text=[NSString stringWithFormat:@"%@%d",NSLocalizedString(@"再康健康秤", nil),(int)(deviceArray.count+1)];
                [alert addButton:NSLocalizedString(@"确定", nil) actionBlock:^(void)
                 {
                     if (textField.text==nil ||[textField.text isEqualToString:@""])
                     {
                         [self SHowMessage:NSLocalizedString(@"设备名称不可为空！", nil) type:showWarning];
                         return ;
                     }
                     info.name=textField.text;
                     NSDictionary *UserDict = info.keyValues;
                     [deviceArray addObject:UserDict];
                     NSString*result= [ToolHelper  dictionaryToJson:deviceArray];
                     [defaults setObject:result forKey:@"DeviceAlls"];
                     [defaults synchronize];
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"UserChange" object:nil];
                     vc.deviceName=textField.text;
                     [self  presentViewController:mainVC animated:YES completion:nil];
                 }];
                [alert addButton:NSLocalizedString(@"取消", nil) actionBlock:^(void){
                    vc.deviceName=textField.text;
                    [self  presentViewController:mainVC animated:YES completion:nil];
                }];
                
                [alert showEdit:self title:NSLocalizedString(@"系统提示", nil) subTitle:NSLocalizedString(@"健康秤绑定", nil) closeButtonTitle:nil duration:0.0f];
                
            }
        }
        [self  presentViewController:mainVC animated:YES completion:nil];
    }
}

@end
